<?php
namespace app\publics\controller\api;
use app\ApiController;
use app\member\model\AccountModel;
use Qcloud\Cos\Api;
use app\member\model\UsersModel;
use think\Db;

/*------------------------------------------------------ */
//-- 公共调用
/*------------------------------------------------------ */
class Index extends ApiController
{
    public function test()
    {
        $ot_user = Db::name('users')->field('role_id,user_id')->where(['pid' => 30541])
            ->where('role_id','in',[1,2])->order('up_agent_time asc')->limit(2)->select();
        dump($ot_user);
        if(count($ot_user) >= 2){

            if($ot_user[0]['role_id'] == 2 || $ot_user[1]['role_id'] == 2){

//                $AccountModels->releaseFreezeFgAmount($this->userInfo['user_id'],$this->userInfo['account']['freeze_fg_amount']);
            }
        }
        exit;
        $dividend_amount = 100;
        $orderInfo['order_type'] = 0;
        $userInfo['user_id'] = 30541;
        $DividendInfo = settings('DividendInfo');
        $DividendSatus = settings('DividendSatus');
        $unfreeze_fg_amount_condition = $DividendInfo['unfreeze_fg_amount'] ? $DividendInfo['unfreeze_fg_amount'] : 0;

        $userModel = new \app\member\model\UsersModel();
        //根据注册时间最早的时间查3个下级用户
        $start_push_User = $userModel->where([
            ['pid', '=', $userInfo['user_id']],
//            ['up_agent_time', '<>', ''],
        ])->select();


        $start_push_Usercount = $userModel->where([
            ['pid', '=', $userInfo['user_id']],
//            ['up_agent_time', '<>', ''],
        ])->count();


        $manzugxIds = '';
        if ($start_push_Usercount > 0) {
            foreach ($start_push_User as $user){
                $manzugxIds .= $user['user_id'] . ',';
            }
            $pull_UserList = rtrim($manzugxIds,',');
        }else{
            $pull_UserList = '30000';
        }


//        $rebate_push_num = $userModel
//            ->where([
//                ['pid', '=', $userInfo['user_id']],
//                ['role_id', '=', 2],
//                ['user_id', 'in', $pull_UserList],
//            ])
//            ->count();
        $rebate_push_num = 0;
        $ot_user = Db::name('users')->field('role_id,user_id')->where(['pid' => $userInfo['user_id']])
            ->where('role_id','in',[1,2])->order('up_agent_time asc')->limit($DividendInfo['rebate_push_num'])->select();
        if(count($ot_user) >= $DividendInfo['rebate_push_num']){
            foreach ($ot_user as $ot){
                if($ot['role_id'] == 2){
                    $rebate_push_num++;
                }
            }
        }

        /*
         * 原来方案
        $rebate_push_num = $userModel
            ->where([
                ['pid', '=', $this->userInfo['user_id']],
                ['role_id', '=', 2],
                //                ['profit_pid', '<>', $userInfo['user_id']],
            ])
            ->count();
        */

        $isrelease = 0;
        $AccountModels = new \app\member\model\AccountModel();
        if ($DividendSatus == 1) {
            if ($rebate_push_num >= $DividendInfo['rebate_push_num'] || $userInfo['isrelease'] == 1) {
                $isrelease = 1;
                $AccountModels->releaseSupport($userInfo['user_id']);
            }

        }

        //设置地方释放扶持金

        $DividendInfo = settings('DividendInfo');
        $dividend_bean = 0;

        /*
        $rebate_push_num = $this->UsersModel
            ->where([
                ['pid', '=', $userInfo['user_id']],
                ['role_id', '=', 2],
                //                ['profit_pid', '<>', $userInfo['user_id']],
            ])
            ->count();
        */
        $AccountModels = new AccountModel();
        if ($DividendInfo['rebate_push_num'] > $rebate_push_num) {
            $total_dividend_amount = $dividend_amount;
            $dividend_amount = 0;
            //$dividend_amount = $status == 'vip' ? $total_dividend_amount : bcdiv($total_dividend_amount * $DividendInfo['balance_rebate'], 100, 2);
            //$dividend_bean = $status == 'vip' ? 0 : bcdiv($total_dividend_amount * $DividendInfo['integral_rebate'], 100, 2);
            if($isrelease == 1){
                $dividend_amount = $total_dividend_amount;
                $dividend_bean = 0;
            }else{
                $dividend_amount = bcdiv($total_dividend_amount * $DividendInfo['balance_rebate'], 100, 2);
                $dividend_bean = bcdiv($total_dividend_amount * $DividendInfo['integral_rebate'], 100, 2);
            }
        } else {
            $AccountModels->releaseSupport($userInfo['user_id']);
        }

        $freeze_fg_amount = 0;
        if($orderInfo['order_type'] == 0){
//            $ot_user = Db::name('users')->field('role_id,user_id')->where(['pid' => $userInfo['user_id']])
//                ->order('user_id asc')->limit($unfreeze_fg_amount_condition)->select();
            $ot_user = Db::name('users')->field('role_id,user_id')->where(['pid' => $userInfo['user_id']])
                ->where('role_id','in',[1,2])->order('up_agent_time asc')->limit($unfreeze_fg_amount_condition)->select();
            if(count($ot_user) >= $unfreeze_fg_amount_condition){
                $is_r = true;
                foreach ($ot_user as $ot){
                    if($ot['role_id'] != 2){
                        $is_r = false;
                        break;
                    }
                }
                if($is_r){
                    $dividend_amount = $dividend_amount + $dividend_bean;
                    $dividend_bean = 0;
                }else{
                    $freeze_fg_amount = $dividend_amount + $dividend_bean;
                }
            }else{
                $freeze_fg_amount = $dividend_amount + $dividend_bean;
            }
        }
        if($freeze_fg_amount){
            $dividend_amount = 0;
            $dividend_bean = 0;
        }
        dump($rebate_push_num);
        exit;
        $DividendModel = new \app\distribution\model\DividendModel();
        $orderInfo  =Db::name('shop_order_info')->where('order_sn','2024040874398')->find();
        $res = $DividendModel->_eval($orderInfo, 'pay', 0);
        die;
        $order_id =205;
        $userModel = new UsersModel();
        $order = \app\shop\model\OrderModel::where("order_id", $order_id)->find();
        $result =$userModel->addLdGrade($order);
        //dump($result);
        //2024010227026
    }
    /*------------------------------------------------------ */
    //-- 获取默认设置
    /*------------------------------------------------------ */
    public function defaultSetting(){
        $rows = (new \app\mainadmin\model\SettingsModel)->where('is_open',1)->select();
        $web_path = config('config.host_path');
        foreach ($rows as $row){
            $row['data'] = htmlspecialchars_decode($row['data']);
            $row['data'] = preg_replace('/<img src=\"\/upload/', '<img src="'.$web_path.'/upload',$row['data']);
            $row['data'] = preg_replace('/<img/', '<img style="width:100%"',$row['data']);
            $setting[$row['name']] = isJson($row['data']);
        }
        if (empty($setting['sms_fun']) == false){
            $setting['sms_public_register'] = $setting['sms_fun']['register'];
            $setting['sms_public_login'] = $setting['sms_fun']['login'];
            $setting['sms_public_forget_password'] = $setting['sms_fun']['forget_password'];
            $setting['sms_public_edit_pay_pwd'] = $setting['sms_fun']['edit_pay_pwd'];
            $setting['sms_public_bind_mobile'] = $setting['sms_fun']['bind_mobile'];
            unset($setting['sms_fun']);
        }
        $data['setting'] = $setting;
        session_start();
        $data['session_id'] = session_id();

        //设置地方释放扶持金
        $DividendInfo = settings('DividendInfo');
        $DividendSatus = settings('DividendSatus');
        $userModel = new \app\member\model\UsersModel();
        //根据注册时间最早的时间查3个下级用户
        $start_push_User = $userModel->where([
            ['pid', '=', $this->userInfo['user_id']],
//            ['up_agent_time', '<>', ''],
        ])->select();

        $start_push_Usercount = $userModel->where([
            ['pid', '=', $this->userInfo['user_id']],
//            ['up_agent_time', '<>', ''],
        ])->count();

        $manzugxIds = '';
        if ($start_push_Usercount > 0) {
            foreach ($start_push_User as $user){
                $manzugxIds .= $user['user_id'] . ',';
            }
            $pull_UserList = rtrim($manzugxIds,',');
        }else{
            $pull_UserList = '30000';
        }


        $rebate_push_num = $userModel
            ->where([
                ['pid', '=', $this->userInfo['user_id']],
                ['role_id', '=', 2],
                ['user_id', 'in', $pull_UserList],
            ])
            ->count();
        /*
        $rebate_push_num = $userModel
            ->where([
                ['pid', '=', $this->userInfo['user_id']],
                ['role_id', '=', 2],
//                ['profit_pid', '<>', $userInfo['user_id']],
            ])
            ->count();
        */
        $rebate_push_num = 0;
        $ot_user = Db::name('users')->field('role_id,user_id')->where(['pid' => $this->userInfo['user_id']])
            ->where('role_id','in',[1,2])->order('up_agent_time asc')->limit($DividendInfo['rebate_push_num'])->select();
        if(count($ot_user) >= $DividendInfo['rebate_push_num']){
            foreach ($ot_user as $ot){
                if($ot['role_id'] == 2){
                    $rebate_push_num++;
                }
            }
        }

        $AccountModels = new \app\member\model\AccountModel();
        if($DividendSatus == 1){
            if ($rebate_push_num >= $DividendInfo['rebate_push_num']) {
                $AccountModels->releaseSupport($this->userInfo['user_id']);
            }
            if($this->userInfo['isrelease'] == 1){
                $AccountModels->releaseSupport($this->userInfo['user_id']);
            }
        }
        //设置地方释放扶持金
        $DividendInfo = settings('DividendInfo');
        $unfreeze_fg_amount_condition = $DividendInfo['unfreeze_fg_amount'] ? $DividendInfo['unfreeze_fg_amount'] : 0;
        if(isset($this->userInfo['account']['freeze_fg_amount']) && $this->userInfo['account']['freeze_fg_amount'] > 0){
//            $ids = Db::name('users')->where(['pid' => $this->userInfo['user_id']])->where('role_id','in',[1,2])->order('up_agent_time asc')->limit(2)->column('user_id');
            $ot_user = Db::name('users')->field('role_id,user_id')->where(['pid' => $this->userInfo['user_id']])
                ->where('role_id','in',[1,2])->order('up_agent_time asc')->limit($unfreeze_fg_amount_condition)->select();
            if(count($ot_user) >= $unfreeze_fg_amount_condition){
                if($ot_user[0]['role_id'] == 2 && $ot_user[1]['role_id'] == 2){

                    $AccountModels->releaseFreezeFgAmount($this->userInfo['user_id'],$this->userInfo['account']['freeze_fg_amount']);
                }
            }
        }

        return $this->success($data);
    }

    /*------------------------------------------------------ */
    //-- 验证码
    /*------------------------------------------------------ */
    public function verify(){
        $session_id = input('session_id','','trim');
        $config =    [
            'fontSize' => 30,// 验证码字体大小
            'length'   => 4,// 验证码位数
            'useNoise' => false,// 关闭验证码杂点
            'codeSet' => '0123456789'
        ];
        $Captcha = new \lib\Captcha($config);
        return $Captcha->entry($session_id);
    }
    /*------------------------------------------------------ */
    //-- 生成自定义随机字符串
    /*------------------------------------------------------ */
    public function getRandstr(){
        $length = input('length',10,'intval');
        $data['str'] = random_str($length);
        return $this->success($data);
    }

    public function upVideo()
    {
        if($_FILES['file']['size'] > 31457280){
            return $this->error('最大支持 30M MB上传.');
        }
        if (strstr($_FILES["file"]['type'],'video/mp4') == false) {
            return $this->error('未能识别文件格式，请核实.');
        }
        $file_type = end(explode('.',$_FILES['file']['name']));
        if (in_array($file_type,['mp4']) == false){
            return $this->error('格式不对，只支持 (apk格式)，请核实.');
        }
        $dir = config('config._upload_').'snap_file/';
        makeDir($dir);
        $file_name = random_str(16).'.'.$file_type;
        move_uploaded_file($_FILES['file']['tmp_name'],$dir.$file_name);
        $data['filename'] = trim($dir.$file_name,'.');
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 公共上传临时图片
    /*------------------------------------------------------ */
    public function upImage(){
        $file = $_FILES['file']['name'];
        $type = input('type','','trim');
        $extend = getFileExtend($file);
        if (in_array($extend[1],['jpg','png']) == false){
            return $this->error('只允许上传jpg、png格式图片.');
        }
        $file_path = config('config._upload_').'snap_file/'.date('m').'/';
        if(!file_exists($file_path)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            makeDir($file_path);
        }
        $file = $file_path.random_str(15).rand(10,99).'.'.$extend[1];

        $res = move_uploaded_file($_FILES['file']['tmp_name'], $file) ;

        if($res == false) {
            return $this->error('上传文件失败.');
        }
        $data['file'] = trim($file,'.');
        $data['type'] = $type;
        return $this->success($data);
    }

    /*------------------------------------------------------ */
    //-- 删除上传的临时图片
    /*------------------------------------------------------ */
    public function removeImage(){
        $this->checkLogin();//验证登陆
        $file = input('file','','trim');
        if (strstr($file,'snap_file') == false){
            return $this->error('此接口只能用于删除临时图片.');
        }
        @unlink('.'.$file);
        return $this->success();
    }
    /**
     * [addOrder 下单]
     */
    public function addOrder()
    {
        $time = date('Y-m-d H:i:s',time());
        $json = '{
                    "create_time": "'.$time.'",
                    "type": 0,                                
                    "out_order_id": "101",                 
                    "openid": "obz8f4-vknNtePru3j8Mb8qbiO_o",
                    "path": "pages/shop/goods/info?goods_id=101",    
                    "scene": 1177,                        
                    "out_user_id": "29891",
                    "order_detail":
                    {
                        "product_infos":
                        [
                            {
                                "out_product_id": "101",
                                "out_sku_id":"0",
                                "product_cnt": 1,
                                "sale_price": 168,   
                                "path": "pages/shop/goods/info?goods_id=101",
                                "title" : "玫瑰金小蛮腰项链",
                                "head_img": "http://baseshop.l.com/upload/gimg/2021/05/609f2c70e8860.png"
                            }
                        ],
                        "pay_info": {
                            "pay_method": "其他",
                            "prepay_id": "42526234625",
                            "prepay_time": "'.$time.'",
                            "pay_method_type":99
                        },
                        "price_info": {        
                            "order_price": 168,
                            "freight": 0,
                            "discounted_price": 0,
                            "additional_price": 0,
                            "additional_remarks": ""
                        }
                    },
                    "delivery_detail": {
                        "delivery_type": 1
                    },
                    "address_info": {
                        "receiver_name": "毛先生",
                        "detailed_address": "天河区沐陂大街",
                        "tel_number": "16624661113",
                        "country": "中国",
                        "province": "广东",
                        "city": "广东",
                        "town": "天河区"
                    }
                }';
        $data = json_decode($json,true);

        $res = (new  \app\weixin\model\WeiXinMpModel)->addOrder($data);

        print_r($res);
    }


    /**
     * [addOrder 下单]
     */
    public function pay()
    {
        $time = date('Y-m-d H:i:s',time());
        $json = '{
                    "order_id":1884852141765296134,
                    "out_order_id": "1",
                    "openid": "obz8f4-vknNtePru3j8Mb8qbiO_o",
                    "action_type": 1,       
                    "action_remark": "", 
                    "transaction_id": "16624661113",      
                    "pay_time": "'.$time.'"      
                }';
        $data = json_decode($json,true);
        // print_r($data);
        $res = (new  \app\weixin\model\WeiXinMpModel)->pay($data);

        print_r($res);
    }

    /**
     * [addOrder 下单]
     */
    public function sendorder()
    {
        $res = (new  \app\weixin\model\WeixinVideoOrderModel)->getCompanyList();
        print_r($res);
    }
    // 腾讯云存储查询存储桶列表
    public function ossTest()
    {
        // $file = request()->file('upload');
        // print_r($_FILES);
        // 引入类库
        require '../extend/storage/oss/storage.php';
        $storage = new \storage();
        // $res = $storage->createBucket('my-test-mao');
        // $res = $storage->getBucketList();
        // $res = $storage->doesBucketExist('my-test-mao');
        // $res = $storage->getBucketMeta();
        // $res = $storage->getBucketInfo('my-test-mao');

        // $res = $storage->deleteBucket('my-test-mao1');
        // print_r($res);

        // $res = $storage->upload('folder/mao_test3.jpg',$_FILES['upload']);
        // if ($res['code'] == 1) {
        //     echo '<img src="'.$res['url'].'">';
        // }

        // $storage->getObject('O1CN01fdWwBh1yVyhywd4c9_!!3851296585-0-lubanu-s.jpg_430x430q90.jpg');
        // $res = $storage->doesObjectExist('mao_test222.jpg');
        // print_r($res);
        // $res = $storage->getSimplifiedObjectMeta('mao_test2.jpg');
        // print_r($res);
        // $storage->listObjects();
        // $res = $storage->copyObject('test.jpg','test222.jpg');
        // print_r($res);
        // $res = $storage->deleteObject('test222.jpg');
        // print_r($res);
        // $res = $storage->deleteObjects(['mao_test2.jpg','mao_test3.jpg']);
        // print_r($res);
    }

    public function cosTest()
    {
        $StorageModel = new \app\mainadmin\model\StorageModel();
        $row = $StorageModel->getRow(settings('uploadType'));
        require '../extend/storage/'.$row['type'].'/storage.php';
        $storage = new \storage();

        // $res = $storage->createBucket('mytestmao1-1259135872');
        // print_r($res);
        // $res = $storage->getBucketList();
        // $res = $storage->deleteBucket('mytestmao1-1259135872');
        // $res = $storage->listObjects();
        // $res = $storage->upload('folder/mao_test2.jpg',$_FILES['upload']);
        // $res = $storage->copyObject('exampleobject.jpg','exampleobject2.jpg');
        // $res = $storage->deleteObjects(['8a447202105291021335493.png','exampleobject.jpg']);
        // print_r($res);
    }
    public function qiniuTest()
    {
        $StorageModel = new \app\mainadmin\model\StorageModel();
        $row = $StorageModel->getRow(settings('uploadType'));
        require '../extend/storage/'.$row['type'].'/storage.php';
        $storage = new \storage();
        // $res = $storage->createBucket('my-test-mao1');
        // print_r($res);
        // $res = $storage->getBucketList();
        // $res = $storage->deleteBucket('my-test-mao1');
        // $res = $storage->listObjects();
        // print_r($_FILES);
        // $res = $storage->upload('folder/mao_test3.jpg',$_FILES['upload']);
        // $res = $storage->copyObject('FodbUKF-EMc2y_nCY_E0LSlxH_pd',rand(100000,9999999).'.jpg');
        // $res = $storage->deleteObject('FodbUKF-EMc2y_nCY_E0LSlxH_pd');
        $res = $storage->deleteObjects(['7383207.jpg','folder/mao_test2.jpg','test3.jpg','test4.jpg','folder/mao_test3.jpg']);
        print_r($res);
    }
    /*<!DOCTYPE html>
        <html>
        <head>
            <title></title>
        </head>
        <body>
            <h1>hello worlds</h1>
            <form action="/index.php/publics/api.index/qiniuTest" method="post" enctype="multipart/form-data">
                <p><input type="file" name="upload"></p>
                <p><input type="submit" value="submit"></p>
            </form>
        </body>
        </html>*/

    public function getWxShare()
    {
        $url = input('url','','trim');
        $wxShare = (new \app\weixin\model\WeiXinModel)->getSignPackage($url);
        $data['wxShare'] = $wxShare;
        $data['token'] = $this->userInfo['token'];
        return $this->success($data);
    }
}
?>
